package com.github.cyf.echarts;

import com.github.cyf.common.util.RuntimeUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.UUID;


/**
 * @author chenyifan
 * @create 2024-08-13 11:09
 */
@Component
@RequiredArgsConstructor
public class EChartsUtil {

    private final EchartsProperties echartsProperties;

    /**
     * 根据 option 数据字符串生成图片
     * @param option
     * @return
     */
    public void generatePic(String option) throws IOException {
        generatePic(echartsProperties.getConvertJs(), option);
    }

    public void generatePic(String jsPath, String option) throws IOException {
        LocalDate now = LocalDate.now();
        String imageName = UUID.randomUUID() + ".png";
        String imagePath = Paths.get(echartsProperties.getImageDir(), String.valueOf(now.getYear()), String.valueOf(now.getMonthValue()), String.valueOf(now.getDayOfMonth()), imageName).toString();
        generatePic(jsPath, option, imagePath);
    }

    /**
     * 执行 echarts-convert.js 脚本，根据 option 数据字符串生成图片
     * @param jsPath echarts-convert.js 路径
     * @param option option数据字符串
     * @param imagePath 生成的图片路径
     */
    public void generatePic(String jsPath, String option, String imagePath) throws IOException {
        if (!StringUtils.hasText(option)) {
            throw new RuntimeException("option数据字符串为空");
        }

        // 将双引号替换为单引号，将 option 写入临时文件
        option = option.replaceAll("\"", "'");
        String optionPath = Paths.get(echartsProperties.getTempDir(), FilenameUtils.getBaseName(imagePath) + ".json").toString();

        File tempOption = new File(optionPath);
        if (!tempOption.getParentFile().exists()) {
            tempOption.getParentFile().mkdirs();
        }
        FileUtils.writeByteArrayToFile(tempOption, option.getBytes(StandardCharsets.UTF_8));

        File image = new File(imagePath);
        if (!image.getParentFile().exists()) {
            image.getParentFile().mkdirs();
        }
        // 执行脚本
        String cmd = String.format("phantomjs %s -infile %s -outfile %s", Paths.get(jsPath), tempOption.getPath(), Paths.get(imagePath));
        RuntimeUtil.exec(echartsProperties.getPhantomjsDir(), cmd, true);
        tempOption.delete();
    }
}